<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Fwadmin\Controller;

use Think\Controller;

/**
 * Description of ActivityController
 *
 * @author T089
 */
class ActivityController extends BaseController {

    //put your code here
    public function index() {
        $viewList = M('act')->order('id desc')->page($_GET['p'] . ',10')->select();
        $count = M('act')->count();
        $Pages = new \Think\Page($count, 10);
        $Page->url = 'page';
        $show = $Pages->show();
        $this->assign('id', $actid);
        $this->assign('viewList', $viewList);
        $this->assign('pages', $show);
        $this->display();
    }

    public function add() {

        $this->assign('data', array());
        $this->assign('id', 0);
        $this->assign('viewList', array());
        $this->display('add');
    }

    public function update() {
        $actid = intval(I('id'));
        $data = D('act')->where(array('id' => $actid))->find();
        $viewList = D('actdetail')->where(array('act_id' => $actid))->select();
        foreach ($viewList as $key => $value) {
            $viewList[$key]['prize_money'] = $value['prize_money'] / 100;
            $viewList[$key]['prize_probability'] = $value['prize_probability'] / 1000000;
        }
        $this->assign('data', $data);
        $this->assign('id', $actid);
        $this->assign('viewList', $viewList);
        $this->display('add');
    }

    public function save() {
        if (!empty($_POST)) {
            $actid = intval(I('id'));
            $data = array(
                'act_name' => I('name'),
                'act_profit' => I('profit'),
            );
            if (!$actid) {
                D('act')->add($data);
                $actid = D('act')->getLastInsID();
            } else {
                D('act')->where(array('id' => $actid))->save($data);
            }
            if (!isset($_POST['prize_id']) || !is_array($_POST['prize_id']) || empty($_POST['prize_id'])) {
                return;
            }
            foreach ($_POST['prize_id'] as $key => $value) {
                $data = array(
                    'act_id' => $actid,
                    'prize_name' => $_POST['prize_name'][$key],
                    'prize_money' => floatval($_POST['prize_money'][$key]) * 100,
                    'prize_probability' => floatval($_POST['prize_probability'][$key]) * 1000000);
                if (!$value) {
                    D('actdetail')->add($data);
                } else {
                    D('actdetail')->where(array('id' => $value))->save($data);
                }
            }
        }
        $this->redirect('/Fwadmin/Activity/update?id=' . $actid);
    }

    public function delete() {
        $actid = intval($_GET['id']);
        D('act')->where(array('id' => $actid))->delete();
    }

    /**
     * 抽奖处理
     * @return type
     */
    public function actdetaildel() {
        $detailid = intval(I('id'));
        D('actdetail')->where(array('id' => $detailid))->delete();
        return $this->ajaxReturn(array('code' => 1));
    }

    public function actcode() {
        $actid = intval($_GET['id']);
        $orderby= isset($_GET['order'])?$_GET['order']:'id';
        $viewList = M('actcode')->where(array('act_id' => $actid))->order($orderby.' desc')->page($_GET['p'] . ',50')->select();
        $count = M('actcode')->where(array('act_id' => $actid))->count();
        $sumarr = M('actcode')->where(array('act_id' => $actid))->field('sum(prize_money) as prize_money')->find();
        $prize_money= isset($sumarr['prize_money'])?$sumarr['prize_money']/100:0;
        $Pages = new \Think\Page($count, 50);
        $Page->url = 'page';
        $show = $Pages->show();
        $this->assign('prize_money',$prize_money);
        $this->assign('id', $actid);
        $this->assign('viewList', $viewList);
        $this->assign('pages', $show);
        $this->display();
    }

    public function actcodeout() {
        $actid = intval($_GET['id']);
        $num = intval($_GET['code_num']);
        if ($num > 50) {
            $nums = 50;
        }
        else{
            $nums=$num;
        }
        $indata = array();
        $outtime = time();
        for ($i = 0; $i < $nums; $i++) {
            $indata[] = array(
                'act_id' => $actid,
                'check_code' => substr(md5(rand(1, 1000000)), 3, 6),
                'add_time' => $outtime
            );
        }
        if (!empty($indata)) {
            D('actcode')->addAll($indata);
        }
        $data = D('actcode')->where(array('act_id' => $actid, 'add_time' => $outtime))->select();
        foreach ($data as $value) {
            $qrimg = $this->qrimg($value['id'], $value['check_code'], $outtime);
            if ($qrimg) {
                D('actcode')->where(array('id' => $value['id']))->save(array('qr_img' => $qrimg));
            }
        }
        $num -= $nums;
        if ($num > 0) {
            $this->redirect('/Fwadmin/Activity/actcodeout',array('id'=>$actid,'code_num'=>$num),1,'正在生成数据...');
        }
        $this->redirect('/Fwadmin/Activity/actcode/id/' . $actid);
    }

    public function qrimg($id, $code, $time) {
        $save_path = isset($_GET['save_path']) ? $_GET['save_path'] : ROOT_PATH . 'Uploads/qrcode/' . date('Ymd',$time) . '/'; //图片存储的绝对路径
        if (!is_dir($save_path)) {
            mkdir($save_path, 0777);
        }
        $web_path = isset($_GET['save_path']) ? $_GET['web_path'] : '/Uploads/qrcode/' . date('Ymd',$time) . '/'; //图片在网页上显示的路径
        $qr_data = 'http://www.hzlwine.com/Mobile/Prize/code?id=' . authcode($id, 'encode') . '&code=' . $code;
        $qr_level = 'H';
        $qr_size = '10';
        $save_prefix = FALSE;

        if ($filename = createQRcode($save_path, $qr_data, $qr_level, $qr_size, $save_prefix)) {
            return $web_path . $filename;
        }
        return '';
    }

    public function download() {
        $filename = ROOT_PATH . 'Uploads/qrcode/load.zip'; // 最终生成的文件名（含路径）// 生成文件
        if (file_exists($filename)) {
            unlink($filename);
        }
        $zip = new \ZipArchive(); // 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if (!$zip->open($filename, \ZipArchive::CREATE)) {
            return '无法打开文件，或者文件创建失败';
        }
        $ids = explode(',', I('id'));
        $type = intval(I('type'));
        $where=array();
        if ($type == 0) {
            foreach ($ids as $key => $value) {
                if (!intval($value)) {
                    unset($ids[$key]);
                } else {
                    $ids[$key] = intval($value);
                }
            }
            if (!is_array($ids) || empty($ids)) {
                return '数据错误';
            }
            $where=array('id' => array('in', implode(',', $ids)));
            
        }
        if ($type == 1) {
           $where=array('load_num'=>0);
        }
         $data = D('actcode')->where($where)->select();
        foreach ($data as $val) {//$fileNameArr 就是一个存储文件路径的数组 比如 array('/a/1.jpg,/a/2.jpg....');
            $zip->addFile(ROOT_PATH . $val['qr_img'], $val['id'] . '.png'); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
        if ($type == 0) {
            D('actcode')->execute('update web_actcode set load_num=load_num+1,load_time=' . time() . ' where id in (' . implode(',', $ids) . ')');
        }
        elseif($type == 1){
            D('actcode')->execute('update web_actcode set load_num=load_num+1,load_time=' . time() . ' where load_num=0');
        }
        $zip->close(); // 关闭
        header("Cache-Control:max-age=0"); //下面是输出下载;
        header("Content-Description:File Transfer");
        header('Content-disposition:attachment;filename=qrcode.zip'); // 文件名
        header("Content-Type:application/zip"); //zip格式的
        header("Content-Transfer-Encoding:binary"); // 告诉浏览器，这是二进制文件
        header('Content-Length:' . filesize($filename)); // 告诉浏览器，文件大小
        @readfile($filename); //输出文件
    }

}
